/// <reference path="sage.util.js" />
/// <reference path="sage.input.__.base.js" />

var GpsInput = BaseInputHandler.extend({
    initialize: function initialize() {
        BaseInputHandler.initialize.call(this, []);
        this.readingCount = 0;
        this.lastLatitude = 0;
        this.lastLongitude = 0;
        this.errorCount = 0;
        this.timerHandle = null;
        this.lastError = null;
        this.lastWasError = false;
        this.gpsHighAccuracy = true;
        this.gpsQueryTimeout = 10000; // milliseconds (10 seconds)
        this.gpsMaximumAge = 20000;// milliseconds (20 seconds)
        this.timerInterval = 1000;
    },
    isAvailable: function isAvailable() {
        return ('geolocation' in navigator);
    },
    sendGpsCoordinates: function sendGpsCoordinates(context) {
        if (this.lastLatitude != context.latitude || this.lastLongitude != context.longitude) {
            this.lastLatitude = context.latitude;
            this.lastLongitude = context.longitude;
            this.readingCount++;
            this.lastWasError = false;
            for (subId in this.subscribers) {
                this.subscribers[subId].fireEvent("gps", context);
            }
        }
    },
    setup: function setup() {
        if (!this.enabled) {
            this.enabled = true;
            var self = this;

            self.timerHandle = setInterval(function () {
                //https://developer.mozilla.org/en-US/docs/Web/API/window.navigator.geolocation.getCurrentPosition#PositionOptions
                navigator.geolocation.getCurrentPosition(
                    function (position) { // on success
                        if (position != null && ("coords" in position)
                            && !isNaN(position.coords.latitude) && !isNaN(position.coords.longitude)) {

                            var context = { prevent: false, latitude: position.coords.latitude, longitude: position.coords.longitude };
                            self.sendGpsCoordinates(context);
                        }
                    },
                    function (error) { // on error
                        self.errorCount++;
                        self.lastError = error;
                        self.lastWasError = true;
                    },
                    { // options
                        maximumAge: self.gpsMaximumAge,
                        timeout: self.gpsQueryTimeout,
                        enableHighAccuracy: self.gpsHighAccuracy
                    }); 
            }, self.timerInterval);
        }
    },
    teardown: function teardown() {
        if (this.enabled) {
            this.enabled = false;
            clearTimeout(this.timerHandle);
        }
    }
});
